package com.centaline.androidsalesblog.activities.mine;

import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.AppCompatTextView;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.api.usercenter.LoginApi;
import com.centaline.androidsalesblog.base.BaseLoginActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.events.WxStatus;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.UserRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.TextFormatUtil;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.PatternFormat;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * 中原找房账号登陆
 * <p/>
 * Created by fusl1 on 2015/12/23.
 * Modify by Lihq on 2016/01/11.
 */
public class CentalineLoginActivity extends BaseLoginActivity implements View.OnClickListener {

    private TextInputLayout til_phone;
    private TextInputLayout til_password;
    private Button btn_login;
    private AppCompatTextView atv_forget_password;
    private EditText phoneEditText, passwordEditText;

    private LoginApi loginApi;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_centaline_login;
    }

    @Override
    protected void findViews() {
        til_phone = (TextInputLayout) findViewById(R.id.til_phone);
        til_password = (TextInputLayout) findViewById(R.id.til_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        atv_forget_password = (AppCompatTextView) findViewById(R.id.atv_forget_password);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initViews() {
        setUniversalToolbar(R.string.title_centaline_login);
        phoneEditText = til_phone.getEditText();
        passwordEditText = til_password.getEditText();
        if (phoneEditText != null &&
                passwordEditText != null) {
            Observable<CharSequence> phoneChangeObservable = RxTextView.textChanges(phoneEditText).skip(1);
            Observable<CharSequence> passwordChangeObservable = RxTextView.textChanges(passwordEditText).skip(1);

            phoneEditText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

            phoneChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
                            Pattern pattern = Pattern.compile(PatternFormat.PhoneNumber);
                            Matcher matcher = pattern.matcher(charSequence);
                            boolean phoneValid = matcher.find();
                            if (phoneValid) {
                                til_phone.setError(null);
                            } else if (til_phone.getError() == null) {
                                til_phone.setError(getString(R.string.error_phone));
                            }
                        }
                    });

            passwordChangeObservable.
                    compose(this.<CharSequence>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CharSequence>() {
                        @Override
                        public void call(CharSequence charSequence) {
                            final boolean passwordValid = charSequence.length() > 5;
                            if (passwordValid) {
                                til_password.setError(null);
                            } else if (til_password.getError() == null) {
                                til_password.setError(getString(R.string.error_password));
                            }
                        }
                    });

            Observable.combineLatest(phoneChangeObservable, passwordChangeObservable,
                    new Func2<CharSequence, CharSequence, Boolean>() {
                        @Override
                        public Boolean call(CharSequence phoneNumber, CharSequence password) {
                            Pattern pattern = Pattern.compile(PatternFormat.PhoneNumber);
                            Matcher matcher = pattern.matcher(phoneNumber);
                            boolean phoneValid = matcher.find();
                            final boolean passwordValid = password.length() > 5;
                            return phoneValid && passwordValid;
                        }
                    })
                    .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            btn_login.setEnabled(aBoolean);
                        }
                    });
        }

        RxView.clicks(btn_login)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        request();
                    }
                });

        RxView.clicks(atv_forget_password)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivityForResult(new Intent(CentalineLoginActivity.this, ForgetPasswordActivity.class),
                                CommonConstant.REQ_LOGIN);
                    }
                });
    }


    private void request() {
        hideKeyboard(til_password);
        showLoadingDialog();
        if (loginApi == null) {
            loginApi = new LoginApi(CentalineLoginActivity.class, UserRo.class, new IResponseListener<UserRo>() {
                @Override
                public void onResponse(UserRo userRo) {
                    UserDo userDo = userRo.getUserDo();
                    int resultNo = userRo.getResultNo();
                    switch (resultNo){
                        case 0:
                            AppConstant.setUserLogin(CentalineLoginActivity.this, userDo);
                            userSave(userDo);
                            break;
                        default:
                            cancelLoadingDialog();
                            snack("手机号或密码错误！");
                            break;
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                    netWorkUnable();
                }
            });
        }
        loginApi.setPhone(TextFormatUtil.formatPhoneNumber(phoneEditText));
        loginApi.setPassWord(passwordEditText.getText().toString());
        loginApi.startRequest();
    }

    /**
     * 保存用户信息
     */
    private void userSave(UserDo userDo) {
        AppConstant.setUserLogin(this, userDo);
        RxDataBase.saveUser(userDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        cancelLoadingDialog();
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    @Override
    protected void otherLoginSuccess() {
        super.otherLoginSuccess();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_login_wechat:
                loginWx = true;
                wXLogin();
                baiduEvent("O2_1_Type","微信");
                break;
            case R.id.img_login_qq:
                qqLogin();
                baiduEvent("O2_1_Type","QQ");
                break;
            case R.id.img_login_weibo:
                sinaLogin();
                baiduEvent("O2_1_Type","sina");
                break;
            default:
                break;
        }
    }

    /**
     * 用户状态改变
     */
    @Subscribe
    public void onEventMainThread(WxStatus wxStatus) {
        if (loginWx) {
            switch (wxStatus.getStatus()) {
                case 0:
                    requestWxAuth(wxStatus.getCode());
                    break;
                case 1:
                    userCancel();
                    break;
                default:
                    break;
            }
        }
        loginWx = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_LOGIN:
                    setResult(RESULT_OK);
                    finish();
                    break;
                default:
                    break;
            }
        }
    }
}
